<?php
/**
 * [WeEngine System] Copyright (c) 2014 WE7.CC
 * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
 */



header('Content-type:text/html; Charset=utf-8');
$mchid = '1507092571';          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$appid = 'wx66a61f6be2e790c6';  //微信支付申请对应的公众号的APPID
$apiKey = '8934e7d15453e97507ef794cf7b0519d';   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥

$wxPay = new WxpayService($mchid,$appid,$apiKey);
$result = $wxPay->notify();
if($result){
	
	
	//file_put_contents("log.txt", json_encode($result));
	define('IN_MOBILE', true);
	require '../../framework/bootstrap.inc.php';
	
	//完成你的逻辑
	//例如连接数据库，获取付款金额$result['cash_fee']，获取订单号$result['out_trade_no']，修改数据库中的订单状态等;
	$icard_order_one=pdo_fetch("SELECT * FROM " . tablename('weisrc_icard_order') . " WHERE ordersn = :ordersn ", array(':ordersn' => $result['out_trade_no']));
	$weid=pdo_getcolumn('weisrc_icard_order', array("ordersn"=>$result['out_trade_no']), 'weid');
	if($icard_order_one['status']==0){
		
		//更新订单状态
		$order_data=array(
				"status"=>1,
				"transid"=>$result['transaction_id'],
				"price"=>floatval($result['total_fee'])/100,
				"dateline"=>time()
		);
		pdo_update('weisrc_icard_order',$order_data,array("ordersn"=>$result['out_trade_no']));
		//1充值，2消费
		if($icard_order_one['ordertype']==1){
			//更新会员余额
			load()->model('mc');
			load()->func('compat.biz');
			$uid = pdo_getcolumn('mc_mapping_fans', array('openid' => $result['openid']), array('uid'));
			$money=floatval($result['total_fee'])/100;
			//file_put_contents("log.txt", $money,FILE_APPEND);
			$value = pdo_getcolumn('mc_members', array('uid' => $uid), 'credit2');
			//file_put_contents("log.txt", $value,FILE_APPEND);
			pdo_update('mc_members', array('credit2' => $value + $money), array('uid' => $uid));
			
			//充值赠送
			$recharge_setting = pdo_fetch("SELECT * FROM " . tablename('weisrc_icard_recharge') 
					. " WHERE weid = :weid AND status=1 AND :nowtime<endtime AND :nowtime>starttime 
					AND :recharge_value>=recharge_value ORDER BY `recharge_value` DESC,`id` DESC LIMIT 1",
					 array(':weid' => $weid, ':nowtime' => TIMESTAMP, ':recharge_value' => $money));
			if (!empty($recharge_setting) && $recharge_setting['give_value'] > 0 && $money>=$recharge_setting['recharge_value'] ) {
				$remark = '充值赠送';
				$log = array();
				$log[0] = $uid;
				$log[1] = $remark;
				mc_credit_update($uid, 'credit2', $recharge_setting['give_value'], $log);
				
			
				//通知
// 				$datetime = date('Y年m月d日H点i分', TIMESTAMP);
// 				$announce_content = "您的尾号{$card['cardnumber']}会员卡于{$datetime}参与充值赠送获得{$recharge_setting['give_value']}元，请及时查收。";
// 				$this->AddAnnounce('充值赠送', $announce_content, $from_user, $this->_announce_card, -1);
			}
			
			
		}
	
		
		//更新会员积分
		pdo_update('weisrc_icard_score_log',array('status'=>1),array("ordersn"=>$result['out_trade_no']));
		$weid=pdo_getcolumn('weisrc_icard_order', array("ordersn"=>$result['out_trade_no']), 'weid');
		//积分设置  recharge_score 充值一元积分 payx_score 消费一元积分
		$obj_score = pdo_fetch("SELECT * FROM " . tablename('weisrc_icard_score') . " WHERE weid = :weid ", array(':weid' => $weid));
		$recharge_score = intval($obj_score['recharge_score']);
		$recharge_totalscore = $money * $recharge_score;
		//file_put_contents("log.txt", $recharge_totalscore,FILE_APPEND);
		$remark = '充值消费赠送积分';
		$log = array();
		$log[0] = $uid;
		$log[1] = $remark;
		mc_credit_update($uid, 'credit1', $recharge_totalscore, $log);
	}
	
	
	
}else{
	echo 'pay error';
}
class WxpayService
{
	protected $mchid;
	protected $appid;
	protected $apiKey;
	public function __construct($mchid, $appid, $key)
	{
		$this->mchid = $mchid;
		$this->appid = $appid;
		$this->apiKey = $key;
	}
	public function notify()
	{
		$config = array(
				'mch_id' => $this->mchid,
				'appid' => $this->appid,
				'key' => $this->apiKey,
		);
		$postStr = file_get_contents('php://input');
		$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
		if ($postObj === false) {
			die('parse xml error');
		}
		if ($postObj->return_code != 'SUCCESS') {
			die($postObj->return_msg);
		}
		if ($postObj->result_code != 'SUCCESS') {
			die($postObj->err_code);
		}
		$arr = (array)$postObj;
		unset($arr['sign']);
		if (self::getSign($arr, $config['key']) == $postObj->sign) {
			echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
			return $arr;
		}
	}
	/**
	 * 获取签名
	 */
	public static function getSign($params, $key)
	{
		ksort($params, SORT_STRING);
		$unSignParaString = self::formatQueryParaMap($params, false);
		$signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
		return $signStr;
	}
	protected static function formatQueryParaMap($paraMap, $urlEncode = false)
	{
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v) {
			if (null != $v && "null" != $v) {
				if ($urlEncode) {
					$v = urlencode($v);
				}
				$buff .= $k . "=" . $v . "&";
			}
		}
		$reqPar = '';
		if (strlen($buff) > 0) {
			$reqPar = substr($buff, 0, strlen($buff) - 1);
		}
		return $reqPar;
	}
}







